<?php
/**
 * @desc Verarbeitet Anfragen des Router 
 */
class controller_blog
{
	private $_model; //model_blog
	private $_view; //model_view

	/**
	 * @desc initialisiert Model / View zur späteren Verwendung 
	 */
	public function __construct()
	{
		$this->_model = new model_blog();
		$this->_view  = view_system::getInstance();
	}

	/**
	 * @desc läd Blogartikel und gibt diese an den View 
	 */
	public function indexAction()
	{
		$this->_view->setValue('content',$this->_model->getArticles());
	}

	/**
	 * @desc gibt ein Forumlar zum Erstellen und Bearbeiten Artikeln aus. 
	 */
	public function editorAction()
	{
		if($_SESSION['loginstatus'] == true)
		{
			$this->_view->setValue('content',self::getFormEditor());
		}
		else
		{
			$this->_view->setValue('content','bitte anmelden');
		}
	}

	public function saveAction()
	{
		if($_SESSION['loginstatus'] == true)
		{
			if(	isset($_POST['text']) &&
				isset($_POST['filename']) &&
				isset($_POST['dir']))
				{
					if(is_dir('files/blog/'.$_POST['dir']))
					{
						file_put_contents('files/blog/'.$_POST['dir'].'/'.$_POST['filename'].'.txt',trim($_POST['text']));
					}
				}
		}
		else
		{
			$this->_view->setValue('content','bitte anmelden');
		}
	}

	/**
	 * @todo in eigene Klasse überführen ???
	 * @return string 
	 */
	public function getFormEditor()
	{
		$form = "<form name=\"formular\" method=\"post\" action=\"/blog/save/\">\n";
		$form .= "\t<p>\n";
		$form .= "\t\t<label>Text:</label><br />\n";
		$form .= "\t\t<textarea name=\"text\" rows=\"8\" cols=\"64\" required=\"required\">TEXT</textarea>\n";
		$form .= "\t</p>\n";
		$form .= "\t<p>\n";
		$form .= "\t\t<label>Dateiname:</label>\n";
		$form .= "\t\t<input type=\"text\" name=\"filename\" required=\"required\" />\n";
		$form .= "\t</p>\n";
		$form .= "\t<p>\n";
		$form .= "\t\t<label>Speicherort:</label>\n";
		$form .= "\t\t<select name=\"dir\">\n";

		foreach($this->_model->getDirs() as $dir)
		{
			$form .= "\t\t<option value =\"".$dir."\">".$dir."</option>\n";
		}
		
		$form .= "\t\t</select>\n";
		$form .= "\t</p>\n";
		$form .= "\t<p>\n";
		$form .= "\t\t<input type=\"submit\" />\n";
		$form .= "\t</p>\n";	
		$form .= "</form>\n";

		return $form;
	}
}